"use client";

import { useState, useEffect } from "react";
import { useLanguage } from "@/contexts/LanguageContext";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Trash2 } from "lucide-react";
import Papa from "papaparse";

export function AssignmentList() {
  const [assignments, setAssignments] = useState<string[]>([]);
  const [newTitle, setNewTitle] = useState("");
  const { t } = useLanguage();

  useEffect(() => {
    const savedAssignments = JSON.parse(
      localStorage.getItem("assignments") || "[]"
    );
    if (savedAssignments.length > 0) {
      setAssignments(savedAssignments);
    } else {
      const initialAssignments = [
        "2024-10-31: The Calendar Project",
        "2025-03-22: Symmetry Drawing",
        "2025-07-01: Spelling Test Term 1 Average",
        "2025-12-25: Presenting Assembly 1",
        "2025-03-21: Math: The Graphing Booklet",
        "2025-12-31: The Yoga Project",
      ];
      setAssignments(initialAssignments);
      localStorage.setItem("assignments", JSON.stringify(initialAssignments));
    }
  }, []);

  const addAssignment = () => {
    if (newTitle.trim()) {
      const updatedAssignments = [...assignments, newTitle.trim()];
      setAssignments(updatedAssignments);
      localStorage.setItem("assignments", JSON.stringify(updatedAssignments));
      setNewTitle("");
    }
  };

  const deleteAssignment = (index: number) => {
    const updatedAssignments = assignments.filter((_, i) => i !== index);
    setAssignments(updatedAssignments);
    localStorage.setItem("assignments", JSON.stringify(updatedAssignments));
  };

  const exportToCSV = () => {
    const csvData = assignments.map((assignment, index) => ({
      Id: index + 1,
      Assignment: assignment,
    }));

    const csv = Papa.unparse(csvData);
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");
    if (link.download !== undefined) {
      const url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", "assignments.csv");
      link.style.visibility = "hidden";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };

  const importFromCSV = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      Papa.parse(file, {
        complete: (results) => {
          const importedData = results.data as {
            Id: string;
            Assignment: string;
          }[];
          const newAssignments = importedData.map((row) => row.Assignment);
          setAssignments(newAssignments);
          localStorage.setItem("assignments", JSON.stringify(newAssignments));
        },
        header: true,
      });
    }
  };

  return (
    <div>
      <h2 className="text-2xl font-bold mb-4">{t("作业列表")}</h2>
      <div className="flex justify-end space-x-2 mb-4">
        <Button onClick={exportToCSV}>{t("导出CSV")}</Button>
        <label htmlFor="import-file" className="cursor-pointer">
          <Input
            id="import-file"
            type="file"
            className="hidden"
            onChange={importFromCSV}
            accept=".csv"
          />
          <span>
            <Button>{t("导入CSV")}</Button>
          </span>
        </label>
      </div>
      <div className="space-y-2 mb-4">
        <Input
          type="text"
          value={newTitle}
          onChange={(e) => setNewTitle(e.target.value)}
          placeholder={t("作业标题")}
        />
        <Button onClick={addAssignment}>{t("添加作业")}</Button>
      </div>
      <ul className="space-y-4">
        {assignments.map((assignment, index) => (
          <li
            key={index}
            className="border p-4 rounded flex justify-between items-center"
          >
            <span>{assignment}</span>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => deleteAssignment(index)}
            >
              <Trash2 className="h-4 w-4" />
            </Button>
          </li>
        ))}
      </ul>
    </div>
  );
}
